<?php include_once( "_db.php" ); //Database ?>
<?php include_once( "funcdef.php" ); //Functions Definition ?>
<?php include_once( "header.php" ); //Header ?>
<?php include_once( "footer.php" ); //Footer ?>
<?php
//include page header
header_template("List", $_SERVER['PHP_SELF'], "icon-th-list");

//db OBJECT invoked!
$db = new DATABASE();
?>
      <div class="row">
        <div class="span6">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
  //Submit button for Create
  $button_submit_name  = "create-list";
  $button_submit_value = "Create";
  //Hidden list id
  $hidden_list_id = "";
  //List for Create
  $resList = array();
  if (isset($_GET["action"]) && isset($_GET["list_id"])) {
    if ($_GET["action"] == "edit") {
      //List for Edit
      //construct SELECT query
      $conds = array();
      $conds[] = array(0); //$param_col;
      $conds[] = array(0); //$param_op;
      $conds[] = array($_GET["list_id"]); //$param_key;
      $query = $db->db_select("list", NULL, $conds);
      //execute SELECT query
      $result = $db->database->query($query);
      //result SELECT query
      $resList = $result->fetchAll(SQLITE_ASSOC);
      //Submit button for Edit
      $button_submit_name  = "edit-list";
      $button_submit_value = "Edit";
      //Hidden list id
      $hidden_list_id = "<input type='hidden' name='list_id' value='".$resList[0]['list_id']."' />";
    }
  }
?>
          <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="application/x-www-form-urlencoded" class="well form-inline">
            <?php echo $hidden_list_id."\n"; ?>
            <label class="control-label" for="list">List</label>
            <input type="text" class="input-xlarge" id="list" name="list" value="<?php echo $resList[0]['list_name']; ?>" />
            <input type="submit" name="<?php echo $button_submit_name; ?>" value="<?php echo $button_submit_value; ?>" class="btn btn-info" />
          </form>
<?php
    if ($_GET["action"] == "link") {
      //List for Link
      //construct SELECT query
      $conds = array();
      $conds[] = array(0); //$param_col;
      $conds[] = array(0); //$param_op;
      $conds[] = array($_GET["list_id"]); //$param_key;
      $query = $db->db_select("list", NULL, $conds);
      //execute SELECT query
      $result = $db->database->query($query);
      //result SELECT query
      $resList = $result->fetchAll(SQLITE_ASSOC);
      //Category for Link
      //construct SELECT query
      $query = $db->db_select("category", NULL, NULL);
      //execute SELECT query
      $result = $db->database->query($query);
      //result SELECT query
      $resCat = $result->fetchAll(SQLITE_ASSOC);
      //construct SELECT query
      $cols = array(1); //$param_col;
      $conds = array();
      $conds[] = array(2); //$param_col;
      $conds[] = array(0); //$param_op;
      $conds[] = array($_GET["list_id"]); //$param_key;
      $query = $db->db_select("category2list", $cols, $conds);
      //execute SELECT query
      $result = $db->database->query($query);
      //result SELECT query
      $resCat2List = $result->fetchAll(SQLITE_ASSOC);
      //Submit button for Link
      $button_submit_name  = "link-list";
      $button_submit_value = "Link";
      //Hidden list id
      $hidden_list_id = "<input type='hidden' name='list_id' value='".$resList[0]['list_id']."' />";
      //Hidden list name
      $hidden_list_name = "<input type='hidden' name='list_name' value='".$resList[0]['list_name']."' />";
?>
          <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="application/x-www-form-urlencoded" class="well form-horizontal">
            <?php echo $hidden_list_id."\n"; ?>
            <?php echo $hidden_list_name."\n"; ?>
            <span class="help-block"><span class="label label-default"><?php echo $resList[0]['list_name']; ?></span></span>
            <div class="control-group">
              <label class="control-label" for="checkCategory">Link to</label>
              <div class="controls">
<?php
      //category(s) existence OK
      if (!empty($resCat)) {
        //loop trough all list(s)
        foreach ($resCat as $cat) {
          if (in_array_2d($cat['category_id'], $resCat2List)) {
            $category_check = " checked";
          } else {
            $category_check = "";
          }
?>
                <label class="checkbox inline" id="checkCategory">
                  <input type="checkbox" name="category_id[]" value="<?php echo $cat['category_id']; ?>"<?php echo $category_check; ?>><?php echo $cat['category_name']."\n"; ?>
                </label>
<?php
        }
?>
              </div>
            </div>
<?php
        $show_select_yes = "";
        $show_select_no = "";
        if ($resList[0]['list_show'] == "yes") {
          $show_select_yes = " selected";
        }
        if ($resList[0]['list_show'] == "no") {
          $show_select_no = " selected";
        }
?>
            <div class="control-group">
              <label class="control-label" for="optionShow">Show</label>
              <div class="controls">
                <select name="list_show" id="optionShow">
                  <option value="yes"<?php echo $show_select_yes; ?>>Yes</option>
                  <option value="no"<?php echo $show_select_no; ?>>No</option>
                </select>
              </div>
            </div>
            <div class="control-group">
              <div class="controls">
                <input type="submit" name="<?php echo $button_submit_name; ?>" value="<?php echo $button_submit_value; ?>" class="btn btn-info" />
              </div>
            </div>
          </form>
<?php
      }
    }
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
  //construct SELECT query
  $query = $db->db_select("list", NULL, NULL);
  //execute SELECT query
  $result = $db->database->query($query);
  //result SELECT query
  $resList = $result->fetchAll(SQLITE_ASSOC);
  //Create List
  if ($_POST['create-list'] == "Create") {
    //Form field check NG
    if ($_POST["list"] == "") {
      printAlert("error", "Oh snap!", "List field is empty.", $_SERVER['PHP_SELF']);
    } else {//Form field check OK
      //Existence check NG
      if (in_array_2d($_POST["list"], $resList)) {
        printAlert("error", "Oh snap!", "List already exist.", $_SERVER['PHP_SELF']);
      } else {//Existence check OK
        //construct INSERT query
        $params = array();
        $params[] = array(1); //$param_col;
        $params[] = array($_POST["list"]); //$param_key;
        $query = $db->db_insert("list", $params);
        //execute INSERT query
        $result = $db->database->query($query);
        //Add list NG
        if ($result == FALSE) {
          printAlert("error", "Oh snap!", "Cannot create List '".$_POST["list"]."'.", $_SERVER['PHP_SELF']);
        } else {//Add list OK
          //INSERT SUCCEED!!!
          printAlert("success", "Well done!", "List '".$_POST["list"]."' successfully created.", $_SERVER['PHP_SELF']);
        }
      }
    }
  }
  //Edit List
  if ($_POST['edit-list'] == "Edit") {
    //Form field check NG
    if ($_POST["list"] == "") {
      printAlert("error", "Oh snap!", "List field is empty.", $_SERVER['PHP_SELF']);
    } else {//Form field check OK
      //ID check NG
      if (!in_array_2d($_POST["list_id"], $resList)) {
        printAlert("error", "Oh snap!", "List ID not exist.", $_SERVER['PHP_SELF']);
      } else {//ID check OK
        //Existence check NG
        if (in_array_2d($_POST["list"], $resList)) {
          printAlert("error", "Oh snap!", "List already exist.", $_SERVER['PHP_SELF']);
        } else {//Existence check OK
          //construct UPDATE query
          $params = array();
          $params[] = array(1); //$param_col;
          $params[] = array($_POST["list"]); //$param_key;
          $conds = array();
          $conds[] = array(0); //$param_col;
          $conds[] = array(0); //$param_op;
          $conds[] = array($_POST["list_id"]); //$param_key;
          $query = $db->db_update("list", $params, $conds);
          //execute UPDATE query
          $result = $db->database->query($query);
          //Edit list NG
          if ($result == FALSE) {
            printAlert("error", "Oh snap!", "Cannot edit List '".$_POST["list"]."'.", $_SERVER['PHP_SELF']);
          } else {//Edit list OK
            //UPDATE SUCCEED!!!
            printAlert("success", "Well done!", "List '".$_POST["list"]."' successfully edited.", $_SERVER['PHP_SELF']);
          }
        }
      }
    }
  }
  //Link List
  if ($_POST['link-list'] == "Link") {
    //construct SELECT query
    $query = $db->db_select("list", NULL, NULL);
    //execute SELECT query
    $result = $db->database->query($query);
    //result SELECT query
    $resList = $result->fetchAll(SQLITE_ASSOC);
    //ID check NG
    if (!in_array_2d($_POST["list_id"], $resList)) {
      printAlert("error", "Oh snap!", "List ID not exist.", $_SERVER['PHP_SELF']);
    } else {//ID check OK
      //construct UPDATE query
      $params = array();
      $params[] = array(2); //$param_col;
      $params[] = array($_POST["list_show"]); //$param_key;
      $conds = array();
      $conds[] = array(0); //$param_col;
      $conds[] = array(0); //$param_op;
      $conds[] = array($_POST["list_id"]); //$param_key;
      $query = $db->db_update("list", $params, $conds);
      //execute UPDATE query
      $result = $db->database->query($query);
      if ($result == FALSE) {
        printAlert("error", "Oh snap!", "Cannot update List '".$_POST["list_name"]."'.", $_SERVER['PHP_SELF']);
      } else {//Edit list OK
        //UPDATE SUCCEED!!!
        //printAlert("success", "Well done!", "List '".$_POST["list_name"]."' successfully updated.", $_SERVER['PHP_SELF']);    
        //construct DELETE params
        $conds = array();
        $conds[] = array(2); //$param_col;
        $conds[] = array(0); //$param_op;
        $conds[] = array($_POST["list_id"]); //$param_key;
        //construct DELETE query
        $query = $db->db_delete("category2list", $conds);
        //execute DELETE query
        $result = $db->database->query($query);
        if ($result == FALSE) {
          printAlert("error", "Oh snap!", "Cannot unlink List '".$_POST["list_name"]."'.", $_SERVER['PHP_SELF']);
        } else {//Edit list OK
          //DELETE SUCCEED!!!
          //printAlert("success", "Well done!", "List '".$_POST["list_name"]."' successfully unlinked.", $_SERVER['PHP_SELF']);
          foreach ($_POST["category_id"] as $cat_id) {
            //construct INSERT params
            $params = array();
            $params[] = array(1, 2); //$param_col;
            $params[] = array($cat_id, $_POST["list_id"]); //$param_key;
            $query = $db->db_insert("category2list", $params);
            //execute INSERT query
            $result = $db->database->query($query);
          }
          if ($result == FALSE) {
            printAlert("error", "Oh snap!", "Cannot link List '".$_POST["list_name"]."'.", $_SERVER['PHP_SELF']);
          } else {//Edit list OK
            //INSERT SUCCEED!!!
            printAlert("success", "Well done!", "List '".$_POST["list_name"]."' successfully linked.", $_SERVER['PHP_SELF']);
          }
        }
      }
    }
  }
} else {
  $error_msg = "This script only works with GET and POST requests.";
  printAlert("error", "Oh snap!", $error_msg, $_SERVER['PHP_SELF']);
}

//Delete List
if (isset($_GET["action"]) && isset($_GET["list_id"])) {
  //construct SELECT query
  $query = $db->db_select("list", NULL, NULL);
  //execute SELECT query
  $result = $db->database->query($query);
  //result SELECT query
  $resList = $result->fetchAll(SQLITE_ASSOC);
  if ($_GET["action"] == "delete") {
    //ID check NG
    if (!in_array_2d($_GET["list_id"], $resList)) {
      printAlert("error", "Oh snap!", "List ID not exist.", $_SERVER['PHP_SELF']);
    } else {//ID check OK
      $conds = array();
      $conds[] = array(0); //$param_col;
      $conds[] = array(0); //$param_op;
      $conds[] = array($_GET["list_id"]); //$param_key;
      $query = $db->db_select("list", NULL, $conds);
      //execute SELECT query
      $result = $db->database->query($query);
      //result SELECT query
      $resList = $result->fetchAll(SQLITE_ASSOC);
      //construct DELETE query
      $query = $db->db_delete("list", $conds);
      //execute DELETE query
      $result = $db->database->query($query);
      //delete list NG
      if ($result == FALSE) {
        printAlert("error", "Oh snap!", "Cannot delete ".$resList[0]['list_name'], $_SERVER['PHP_SELF']);
      } else {//delete list OK
        //DELETE SUCCEED!!!
        printAlert("success", "Well done!", $resList[0]['list_name']." successfully deleted", $_SERVER['PHP_SELF']);
        //CHECK FOR category2list
        //construct DELETE params
        $conds = array();
        $conds[] = array(2); //$param_col;
        $conds[] = array(0); //$param_op;
        $conds[] = array($_GET["list_id"]); //$param_key;
        //construct DELETE query
        $query = $db->db_delete("category2list", $conds);
        //execute DELETE query
        $result = $db->database->query($query);
        //delete list link NG
        if ($result == FALSE) {
          printAlert("error", "Oh snap!", "Cannot delete ".$resList[0]['list_name']." link", $_SERVER['PHP_SELF']);
        } else {//delete list link OK
          //DELETE SUCCEED!!!
          printAlert("success", "Well done!", $resList[0]['list_name']." link successfully deleted", $_SERVER['PHP_SELF']);
        }
      }
    }
  }
}

//construct SELECT query
$query = $db->db_select("list", NULL, NULL);
//execute SELECT query
$result = $db->database->query($query);
//result SELECT query
$resList = $result->fetchAll(SQLITE_ASSOC);
//List list(s)
?>
          <span class="label label-inverse">Edit / Delete List</span>
          <div class="well well-small">
            <p>
<?php
//list(s) existence OK
if (!empty($resList)) {
  //loop trough all list(s)
  foreach ($resList as $list) {
    $list_edit_href = $_SERVER['PHP_SELF']."?action=edit&list_id=".$list['list_id'];
    $list_delete_href = $_SERVER['PHP_SELF']."?action=delete&list_id=".$list['list_id'];
    $list_link_href = $_SERVER['PHP_SELF']."?action=link&list_id=".$list['list_id'];
?>
              <span class="label label-default"><?php echo $list['list_name']; ?></span><a class="label label-info" href="<?php echo $list_edit_href; ?>">&nbsp;&#45;&nbsp;</a><a class="label label-important" href="<?php echo $list_delete_href; ?>">&nbsp;&#215;&nbsp;</a><a class="label label-inverse" href="<?php echo $list_link_href; ?>">&nbsp;&#172;&nbsp;</a>&nbsp;
<?php
  }
}
?>
            </p>
          </div>
          <!-- SAMPLE NAVBAR -->
          <div class="navbar">
            <div class="navbar-inner">
              <ul class="nav">
<?php
//list(s) existence OK
if (!empty($resList)) {
  $navlist = navlist_construction($db);
  foreach ($navlist as $nav) {
    $list_name = $nav[0];
    if (count($nav) > 1) {
?>
                <li class="dropdown">
<?php
      foreach ($nav as $key => $cat) {
        if ($key == 0) {
?>
                  <a class="dropdown-toggle" id="drop<?php echo $key; ?>" role="button" data-toggle="dropdown"><?php echo $nav[$key]; ?> <b class="caret"></b></a>
                  <ul class="dropdown-menu" role="menu" aria-labelledby="drop<?php echo $key; ?>">
<?php
        } else {
?>
                    <li><a role="menuitem" tabindex="-1" href="#"><?php echo $nav[$key]; ?></a></li>
<?php
        }
      }
?>
                  </ul>
                </li>
<?php
    } else {
?>
                <li><a><?php echo $list_name; ?></a></li>
<?php
    }
  }
}
?>
              </ul>
            </div>
          </div>
        </div>
      </div>
<?php
//include page footer
footer_template();
?>
